package net.godcode.olivenotes.components;

import java.text.SimpleDateFormat;

import net.godcode.olivenotes.entities.Post;

import org.apache.tapestry.ClientElement;
import org.apache.tapestry.ComponentResources;
import org.apache.tapestry.Link;
import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.PageRenderSupport;
import org.apache.tapestry.annotations.AfterRender;
import org.apache.tapestry.annotations.BeforeRenderTemplate;
import org.apache.tapestry.annotations.BeginRender;
import org.apache.tapestry.annotations.Environmental;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.annotations.SupportsInformalParameters;
import org.apache.tapestry.corelib.base.AbstractLink;
import org.apache.tapestry.ioc.annotations.Inject;

@SupportsInformalParameters
/**
 * ViewPostLink creates a permalinkable title to its respective post.
 * 
 * @author Chris Lewis Jan 11, 2008 <chris@thegodcode.net>
 * @version $Id: ViewPostLink.java 32 2008-01-22 15:14:31Z burningodzilla $
 */
public class ViewPostLink extends AbstractLink implements ClientElement {
	
	/**
	 * The Post from which to construct the context.
	 */
	@SuppressWarnings("unused")
	@Parameter(required = true)
	private Post post;
	
	@Inject
	private ComponentResources resources;

	@Environmental
	private PageRenderSupport support;
	
	private String clientId;
	
	private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
	
	@BeginRender
	void beginRender(MarkupWriter writer) {
		clientId = support.allocateClientId(resources.getId());
		
		//TODO CENTRALIZE!
		Object[] context = new Object[] { null, null, null, post.getName() }; 
		String[] ymd = format.format(post.getCreated()).split("/", 3);
		System.arraycopy(ymd, 0, context, 0, 3);
		
		Link link = resources.createPageLink("blog/viewpost", true, context);
		writeLink(writer, clientId, link);
	}
	
	@BeforeRenderTemplate
	boolean beforeRenderTemplate(MarkupWriter writer) {
		writer.write(post.getTitle());
		return false;
	}
	
	@AfterRender
	void afterRender(MarkupWriter writer) {
		writer.end();
	}
	
	public String getClientId() {
		return clientId;
	}
	
}